﻿/* System.Compute: a Computation Framework for .NET/Mono
 * Copyright (C) 2011 Ralf "raboni" Boeckhorst
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 */

using System.Runtime.InteropServices;

namespace System.Compute.OpenCL
{
    public sealed class DeviceImage : ICloneable, IDisposable
    {
        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern IntPtr clCreateImage2D(IntPtr context, MemoryFlags flags, ImageFormat[] image_format, SizeT image_width, SizeT image_height, SizeT image_row_pitch, IntPtr host_ptr, out ErrorCode errcode_ret);

        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern IntPtr clCreateImage3D(IntPtr context, MemoryFlags flags, ImageFormat[] image_format, SizeT image_width, SizeT image_height, SizeT image_depth, SizeT image_row_pitch, SizeT image_slice_pitch, IntPtr host_ptr, out ErrorCode errcode_ret);

        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern ErrorCode clGetImageInfo(IntPtr image, ImageInfo param_name, SizeT param_value_size, ref ImageFormat param_value, SizeT param_value_size_ret);

        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern ErrorCode clGetImageInfo(IntPtr image, ImageInfo param_name, SizeT param_value_size, ref SizeT param_value, SizeT param_value_size_ret);

        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern ErrorCode clGetSupportedImageFormats(IntPtr context, MemoryFlags flags, MemoryObjectType image_type, uint num_entries, int[] image_formats, uint num_image_formats);

        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern ErrorCode clGetSupportedImageFormats(IntPtr context, MemoryFlags flags, MemoryObjectType image_type, uint num_entries, int[] image_formats, out uint num_image_formats);

        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern ErrorCode clRetainMemObject(IntPtr memobj);

        [DllImport("opencl.dll", ExactSpelling = true)]
        static extern ErrorCode clReleaseMemObject(IntPtr memobj);

        public ImageFormat Format
        {
            get
            {
                ImageFormat ret = new ImageFormat();
                ErrorCode res = clGetImageInfo(Handle, ImageInfo.Format, Marshal.SizeOf(typeof(ImageFormat)), ref ret, 0);
                if (res != ErrorCode.Success)
                    throw new OpenCLException(res);
                return ret;
            }
        }

        public SizeT ElementSize
        {
            get
            {
                SizeT ret = new SizeT();
                ErrorCode res = clGetImageInfo(Handle, ImageInfo.ElementSize, ret.Size, ref ret, 0);
                if (res != ErrorCode.Success)
                    throw new OpenCLException(res);
                return ret;
            }
        }

        public SizeT RowPitch
        {
            get
            {
                SizeT ret = new SizeT();
                ErrorCode res = clGetImageInfo(Handle, ImageInfo.RowPitch, ret.Size, ref ret, 0);
                if (res != ErrorCode.Success)
                    throw new OpenCLException(res);
                return ret;
            }
        }

        public SizeT SlicePitch
        {
            get
            {
                SizeT ret = new SizeT();
                ErrorCode res = clGetImageInfo(Handle, ImageInfo.SlicePitch, ret.Size, ref ret, 0);
                if (res != ErrorCode.Success)
                    throw new OpenCLException(res);
                return ret;
            }
        }

        public SizeT Width
        {
            get
            {
                SizeT ret = new SizeT();
                ErrorCode res = clGetImageInfo(Handle, ImageInfo.Width, ret.Size, ref ret, 0);
                if (res != ErrorCode.Success)
                    throw new OpenCLException(res);
                return ret;
            }
        }

        public SizeT Height
        {
            get
            {
                SizeT ret = new SizeT();
                ErrorCode res = clGetImageInfo(Handle, ImageInfo.Height, ret.Size, ref ret, 0);
                if (res != ErrorCode.Success)
                    throw new OpenCLException(res);
                return ret;
            }
        }

        public SizeT Depth
        {
            get
            {
                SizeT ret = new SizeT();
                ErrorCode res = clGetImageInfo(Handle, ImageInfo.Depth, ret.Size, ref ret, 0);
                if (res != ErrorCode.Success)
                    throw new OpenCLException(res);
                return ret;
            }
        }

        internal IntPtr Handle;

        internal DeviceImage(IntPtr handle)
        {
            Handle = handle;
        }

        public static DeviceImage Create2DImage(Context context, MemoryFlags flags, ImageFormat format, SizeT width, SizeT height, SizeT row_pitch)
        {
            flags = (MemoryFlags)((long)flags % 8); // Schneidet Alloc, Use und CopyHostPtr ab
            ErrorCode res;
            DeviceImage img = new DeviceImage(clCreateImage2D(context.Handle, flags, new ImageFormat[] { format }, width, height, row_pitch, IntPtr.Zero, out res));
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            return img;
        }

        public static DeviceImage Create2DImage(Context context, MemoryFlags flags, ImageFormat format, SizeT width, SizeT height, SizeT row_pitch, object initValue)
        {
            flags = (MemoryFlags)((long)flags % 8); // Schneidet Alloc, Use und CopyHostPtr ab
            ErrorCode res;
            GCHandle h = GCHandle.Alloc(initValue, GCHandleType.Pinned);
            DeviceImage img = new DeviceImage(clCreateImage2D(context.Handle, flags | (MemoryFlags)32, new ImageFormat[] { format }, width, height, row_pitch, h.AddrOfPinnedObject(), out res));
            h.Free();
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            return img;
        }

        public static DeviceImage Create3DImage(Context context, MemoryFlags flags, ImageFormat format, SizeT width, SizeT height, SizeT depth, SizeT row_pitch, SizeT slice_pitch)
        {
            flags = (MemoryFlags)((long)flags % 8); // Schneidet Alloc, Use und CopyHostPtr ab
            ErrorCode res;
            DeviceImage img = new DeviceImage(clCreateImage3D(context.Handle, flags, new ImageFormat[] { format }, width, height, depth, row_pitch, slice_pitch, IntPtr.Zero, out res));
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            return img;
        }

        public static DeviceImage Create3DImage(Context context, MemoryFlags flags, ImageFormat format, SizeT width, SizeT height, SizeT depth, SizeT row_pitch, SizeT slice_pitch, object initValue)
        {
            flags = (MemoryFlags)((long)flags % 8); // Schneidet Alloc, Use und CopyHostPtr ab
            ErrorCode res;
            GCHandle h = GCHandle.Alloc(initValue, GCHandleType.Pinned);
            DeviceImage img = new DeviceImage(clCreateImage3D(context.Handle, flags, new ImageFormat[] { format }, width, height, depth, row_pitch, slice_pitch, h.AddrOfPinnedObject(), out res));
            h.Free();
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            return img;
        }

        public static ImageFormat[] GetSupportedImageFormats(Context context, MemoryObjectType image_type, MemoryFlags flags)
        {
            uint num_image_formats;
            ErrorCode res = clGetSupportedImageFormats(context.Handle, flags, image_type, 0, null, out num_image_formats);
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            int[] tmp = new int[num_image_formats * 2];
            res = clGetSupportedImageFormats(context.Handle, flags, image_type, num_image_formats, tmp, 0);
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            ImageFormat[] formats = new ImageFormat[num_image_formats];
            for (int i = 0; i < num_image_formats * 2; i += 2)
            {
                formats[i / 2].ChannelOrder = (ChannelOrder)tmp[i];
                formats[i / 2].ChannelDataType = (ChannelType)tmp[i + 1];
            }
            return formats;
        }

        public object Clone()
        {
            ErrorCode res = clRetainMemObject(Handle);
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            return new DeviceBuffer(Handle);
        }

        public void Dispose()
        {
            ErrorCode res = clReleaseMemObject(Handle);
            if (res != ErrorCode.Success)
                throw new OpenCLException(res);
            Handle = IntPtr.Zero;
        }
    }
}
